require 'sequel/sqlite'

class Node < DB[:nodes].model
  default_accessor :path
  
  belongs_to :parent, :model => Node
    Node[:id => parent_id]
  
  belongs_to :producer, :model => Session
    Session[:id => producer_id]
  
  has_many :attributes, :key => :node_id, :model => Attribute
    Attribute.filter(:node_id => id)
end

module Sequel
  class NewModel
    class Record
      def initialize(values)
        @values = values
      end
    end
    
    def self.set_dataset(dataset)
      @dataset = dataset
      @dataset.model_class = self::Record
    end
    def self.dataset; @dataset || (raise "Dataset not defined"); end
    
    def self.default_accessor(column)
      meta_def(:[]) do |arg|
        dataset[arg.is_a?(Hash) ? arg : {column => arg}]
      end
    end
  end
  
  class Database
    def model(source, &block)
      c = Class.new(NewModel)
      c.class_eval "class Record < Sequel::NewModel::Record; end"
      c.set_dataset(source.is_a?(Dataset) ? source : self[source])
      c.class_eval(&block) if block
      c
    end
  end
end

require 'logger'
DB = Sequel.open 'sqlite:/:memory:', :logger => Logger.new(STDOUT)
DB.create_table :nodes do
  primary_key :id, :integer, :auto_increment => true
  column :path, :text
end

class Nodes < DB.model(:nodes)
  default_accessor :path
end

# Nodes = DB.model(:nodes) do
#   default_accessor :path
# end

DB[:nodes] << {:path => 'abc'}
node = Nodes['abc']
p node

